using QFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Unity.VisualScripting;

public class AgvController : MonoBehaviour, IController
{
    [SerializeField]
    private List<AGVObject> agvList = new List<AGVObject>();
    [SerializeField]
    private float timeInterval;

    private float durationTime = 0;

    //[SerializeField]
    //Transform MapParent;
    private void Awake()
    {
        OnValidate();
        this.RegisterEvent<UpdateAgvInfoEvent>(OnUpdateAgvInfo).UnRegisterWhenGameObjectDestroyed(this);
        this.RegisterEvent<ChangeMapDatasEvent>(OnChangeConfigInfo).UnRegisterWhenGameObjectDestroyed(this);
    }
    private void OnValidate()
    {
        RequestUrl.intervalTime = timeInterval;
    }

    // Start is called before the first frame update
    void Start()
    {
        foreach (var agv in agvList)
            this.GetSystem<ISelectItemSystem>().AddSelectable(agv);
        durationTime = timeInterval;
    }

    private async UniTask UpdateAgvInfo()
    {
        while (this)
        {
            this.SendCommand(new UpdateAgvInfoCommand());
            await UniTask.Delay(System.TimeSpan.FromSeconds(timeInterval));
        }
    }

    private void OnUpdateAgvInfo(UpdateAgvInfoEvent e)
    {
        foreach(var ndcInfo in this.GetModel<IAgvModel>().NdcInfoDic)
        {
            if(agvList.Exists(t => t.Agvid == ndcInfo.Key))
            {
                agvList.Find(t => t.Agvid == ndcInfo.Key).AgvData.Value = ndcInfo.Value;
            }
        }
    }

    private void OnChangeConfigInfo(ChangeMapDatasEvent e)
    {
        foreach (var agv in agvList)
        {
            agv.zeroPoint = this.GetSystem<IMapSystem>().MapDatas[agv.mapInScene.ToString()].CoordinateOrigin;
            agv.directionModify = this.GetSystem<IMapSystem>().MapDatas[agv.mapInScene.ToString()].mapModifiedDirection;
                                //this.GetModel<IConfigModel>().MapInfos.Find(t => t.MapName == agv.mapInScene.ToString()).ModifiedDirectionInMap;
        }
    }

    public IArchitecture GetArchitecture()
    {
        return DigitalTwin_GeLinMei_2.Interface;
    }
}